import CimManager from './CimManager.js'
import global from '@/config'

export default class MSocket extends CimManager {
    socketTask: any
    isLogOut: boolean
    function: any
    constructor() {
        super()
        this.socketTask = undefined
        this.isLogOut = false
        this.function = {
            message: undefined,
            error: undefined,
            close: undefined,
            open: undefined
        }
    }

    startSocket(data: any, fun: any) {
        this.function = fun
        this.socketTask = uni.connectSocket({
            url: global.SOCKET_API,
            method: 'GET',
            complete: err => {}
        })
        this.onOpen(data)
        this.onError()
    }

    onOpen(data: any) {
        this.socketTask.onOpen((res: any) => {
            this.send({
                data: super.getBindAccountData(`${data.userId}`, `${data.userType}`)
            })
            this.startHeartbeat()
            this.onMessage()
            this.onClose()
            if (this.function.open && this.function.open instanceof Function) {
                this.function.open(res)
            }
        })
    }

    startHeartbeat() {
        setTimeout(() => {
            this.send({
                data: super.getHeartbeatResponseData(),
                success: () => {
                    this.startHeartbeat()
                }
            })
        }, 60000)
    }

    isConnected() {
        return new Promise((resolve, reject) => {
            try {
                this.send({
                    data: super.getHeartbeatResponseData(),
                    success: () => {
                        resolve('')
                    },
                    error: () => {
                        reject()
                    }
                })
            } catch {
                reject()
            }
        })
    }

    send({ data, success, error }: { data: any; success?: Function; error?: Function }) {
        this.socketTask.send({
            data,
            success: () => {
                // console.log('数据发送成功')
                if (success && success instanceof Function) {
                    success()
                }
            },
            fail: (err: any) => {
                // console.log('数据发送失败', err)
                if (error && error instanceof Function) {
                    error(err)
                }
            }
        })
    }

    closeSocket(isLogOut: boolean) {
        this.isLogOut = isLogOut ? true : false
        this.socketTask.close({
            code: 3009,
            reason: '断开连接',
            success: () => {
                console.log('连接关闭')
            },
            fail: (err: any) => {
                console.log('连接关闭失败', err)
            }
        })
    }

    setIsLogOut(isLogOut: boolean) {
        this.isLogOut = isLogOut
    }

    onMessage() {
        this.socketTask.onMessage((res: any) => {
            console.log(this.function)
            if (this.function.message && this.function.message instanceof Function) {
                super.innerOnMessageReceived(res, this.function.message)
            } else {
                console.log('服务器发送数据：' + res.data)
            }
        })
    }

    onClose() {
        this.socketTask.onClose(() => {
            console.log('connection closed')
            if (this.function.close && this.function.close instanceof Function) {
                this.function.close({
                    isLogOut: this.isLogOut
                })
            }
        })
    }

    onError() {
        this.socketTask.onError((errMsg: any) => {
            if (this.function.error && this.function.error instanceof Function) {
                this.function.error(errMsg)
            }
        })
    }
}
